package com.wang.qiniuyun.controller;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.sun.xml.internal.messaging.saaj.util.ByteInputStream;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Arrays;

/**
 * @author: wang
 * @date: 2021/7/30 16:53
 * @description:
 */
@Controller
public class FileUploadController {

    @RequestMapping("upload")
    public String upload(MultipartFile file, Model m){

        //...生成上传凭证，然后准备上传
        String accessKey = "ZCYIKmItzVNAYs95WpynVh6n2m2Qv7F9UA23J_mX";
        String secretKey = "mtaoXVUWZ9ja7O-XF5f8oW-0Vf23f_7YISqqj1nC";
        String bucket = "wuqixiaowei";

        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.huanan());   // 注意修改 region 为所选仓库的地址

        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);

        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = null;

        try {
            byte[] uploadBytes = file.getBytes();
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);

            try {
                Response response = uploadManager.put(uploadBytes, key, upToken);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                m.addAttribute("path","http://qx1u4e0ll.hn-bkt.clouddn.com/"+putRet.key);           // 返回文件地址
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
            }
        } catch (UnsupportedEncodingException | FileNotFoundException ex) {
            //ignore
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "show";
    }
}

